<?php

namespace app\index\controller;

use app\common\controller\Base;


use app\common\model\Appeal;
use app\common\model\BusinessMember;
use app\common\model\BusinessStore;
use app\common\model\Order;
use app\common\model\OrderModel;
use app\common\model\UploadMobile;
use app\common\model\UserModel;

use think\Config;
use think\Db;
use think\Log;
use think\Request;
use think\Validate;
use wechat\WXBizDataCrypt;


class User extends Base
{

    /**
     * @Notes:获取open_id
     * @Interface getOpenId
     * @param Request $request
     * @author: kevin.yong
     * @Time: 2020/4/2 0002 14:30
     */
    public function getOpenId(Request $request)
    {
        $rule = [
            'code' => ['require'],
        ];
        $message = [
            'code.require' => 'code不能为空'
        ];

        $validate = Validate::make($rule, $message);
        $result = $validate->check($request->post());
        if (!$result) {
            $this->failed($validate->getError());
        }
        extract($request->post());
        $config = $this->WECHAT_CONFIG;
        $url = $this->WECHAT_URL;

        $url = $url . "?appid=" . $config['appId'] . "&secret=" . $config['appSecret'] . "&js_code=" . $code . "&grant_type=authorization_code";

        $result = curl_get($url);
        $result = json_decode($result, true);

        if (isset($result['session_key']) && isset($result['openid'])) {

            $this->successful('获取成功', ['open_id' => $result['openid']]);
        } else {
            $this->failed('获取失败', []);
        }

    }

    /**
     * @Notes:登陆以及保存更新用户信息
     * @Interface login
     * @param Request $request
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author: kevin.yong
     * @Time: 2020/4/2 0002 14:30
     */
    public function login(Request $request)
    {
        $rule = [
            'open_id' => ['require'],
            'user_name' => ['require'],
            'pic' => ['require'],
        ];
        $message = [
            'open_id.require' => 'open_id不能为空',
            'user_name.require' => '昵称不能为空',
            'pic.require' => '头像不能为空',
        ];

        $validate = Validate::make($rule, $message);
        $result = $validate->check($request->post());
        if (!$result) {
            $this->failed($validate->getError());
        }
        extract($request->post());
        $model = UserModel::hasOpenId($open_id);
        //处理数据入库
        if (!$model) {
            $data = [
                'open_id' => $open_id,
                'user_name' => isset($user_name) ? $user_name : "",
                'mobile' => isset($mobile) ? $mobile : "",
                'pic' => isset($pic) ? $pic : "",
                'province' => isset($province) ? $province : "",
                'city' => isset($city) ? $city : "",
                'district' => isset($district) ? $district : "",
                'address' => isset($address) ? $address : "",
                'create_time' => time(),
                'login_time' => time(),
            ];
            UserModel::create($data);
        } else {
            $model->user_name = isset($user_name) ? $user_name : "";
            $model->pic = isset($pic) ? $pic : "";
            $model->login_time = time();
            $model->force()->save();
        }

        $userInfo = UserModel::hasOpenId($open_id)->toArray();
        $this->successful('登陆成功', $userInfo);
    }


    /**
     * @Notes:登陆以及保存更新用户信息
     * @Interface login
     * @param Request $request
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author: kevin.yong
     * @Time: 2020/4/2 0002 14:30
     */
    public function getUserInfo(Request $request)
    {
        $rule = [
            'user_id' => ['require'],
        ];
        $message = [
            'user_id.require' => '请先登录'
        ];

        $validate = Validate::make($rule, $message);
        $result = $validate->check($request->post());
        if (!$result) {
            $this->failed($validate->getError());
        }
        extract($request->post());
        $model = UserModel::hasUserId($user_id);
        if (!$model) {
            $this->failed('请先登录');
        }

        $this->successful('获取成功', $model->toArray());
    }


    /**
     * @Notes:获取用户手机号
     * @Interface getUserPhone
     * @param Request $request
     * @author: kevin.yong
     * @Time: 2020/4/2 0002 13:50
     */
    public function getUserMobile(Request $request)
    {

        $rule = [
            'open_id' => ['require'],
            'sessionKey' => ['require'],
            'encryptedData' => ['require'],
            'iv' => ['require'],
        ];
        $message = [
            'open_id.require' => 'open_id不能为空',
            'sessionKey.require' => 'sessionKey不能为空',
            'encryptedData.require' => 'encryptedData不能为空',
            'iv.require' => 'iv不能为空',
        ];

        $validate = Validate::make($rule, $message);
        $result = $validate->check($request->post());
        if (!$result) {
            $this->failed($validate->getError());
        }
        extract($request->post());

        $config = $this->WECHAT_CONFIG;

        $wx = new WXBizDataCrypt($config['appId'], $sessionKey);//微信解密函数

        $errCode = $wx->decryptData($encryptedData, $iv, $data = "");//微信解密函数
        Log::record('errCode======', $errCode);
        if ($errCode == 0) {
            $data = json_decode($data, true);
            $phoneNumber = $data['phoneNumber'];

            return $this->successful("获取成功", ["mobile" => $phoneNumber]);
        } else {
            return $this->failed("获取失败");
        }
    }


    /**
     * @Notes:分享小程序
     * @Interface shareUser
     * @param Request $request
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author: kevin.yong
     * @Time: 2020/4/2 0002 13:39
     */
    public function shareUser(Request $request)
    {


        $rule = [
            'user_id' => ['require'],
        ];
        $message = [
            'user_id.require' => '请先登录',
        ];

        $validate = Validate::make($rule, $message);
        $result = $validate->check($request->post());
        if (!$result) {
            $this->failed($validate->getError());
        }

        extract($request->post());

        $model = UserModel::hasUserId($user_id);

        if (!$model) {
            $this->failed('请先登录');
        }

        $model->share_num = $model->share_num + 1;

        $model->force()->save() ? $this->successful('分享成功') : $this->failed('分享失败');


    }


}

